
package cn.hpclub.server.controller.admin.spreadmember;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import cn.hpclub.server.model.*;
import cn.hpclub.server.util.Utils;
import cn.hpclub.server.util.excel.ExcelLogs;
import cn.hpclub.server.util.excel.ExcelUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.render.JsonRender;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Duang;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.controller.admin.BaseAdminController;
import cn.hpclub.server.service.BusinessAuthConfigService;
import cn.hpclub.server.service.TariffClassService;
import cn.hpclub.server.service.TariffService;
import cn.hpclub.server.util.InterfaceUtil;

/**
 * 泛店员主题模块授权类
 */
public class SpreadMemberAuthConfigController extends BaseAdminController<SpreadMemberBusinessAuthConfig>{
    private static final Logger logger                  = LoggerFactory
            .getLogger(SpreadMemberAuthConfigController.class);
    public static final int     UI_PAGER_NUMBER_DEFAULT = 1;                    // UI默认起始页
    public static final int     UI_PAGER_SIZE_DEFAULT   = 10;                   // UI页容量
    public static final String  KEY_OPERATION           = "operation";          // 当前是新增配置还是编辑配置
    public static final String  KEY_TYPE                = "type";               // 当前操作的是哪个
    public static final String  LIST_SELECT_TYPE        = "list_select_type";   // 当前权限列表是哪个业务类型下拉选项
    public static final String  KEY_FLOW_ID             = "flowId";
    public static final String  KEY_IDS                 = "ids";
    public static final String  KEY_BUSINESS            = "config_business";    // 所属业务值，主题配置时为0
    public static final String  KEY_BUSINESS_ID         = "config_business_id"; // 具体的哪个业务(id)，主题配置时是主题id
    public static final String  KEY_CREATOR_ORG_ID      = "creator_org_id";
    private static final String URL_TEMPLATE  = "/template/admin/file/泛店员授权人员导入模版-大掌柜.xls";

    public static final int     ENTER_TYPE_THEME        = 1;                    // 配置入口类型：1-泛店员主题权限配置
    public static final int     ENTER_TYPE_BUSINESS     = 2;                    // 配置入口类型：2-泛店员业务权限配置
    // public static final int SM_BUSINESS_TYPE_START = 1000; //
    // 非资费类业务类型值从1000开始



    // ------------------------------------------主题权限配置部分--------------------------------------------------------------
    /**
     * 
     * @Title: themeList
     * @Description:主题配置列表
     */
    public void themeList(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        // 主题只有管理员能创建和配置授权
        // if(!searchInfo.containsKey("org_id") ||
        // "-1".equals(searchInfo.get("org_id"))){
        // searchInfo.put("org_id", InterfaceUtil.getOrgId() + "");
        // }
        // int org_id = Integer.parseInt(searchInfo.get("org_id"));
        // setAttr("curr_org_id", org_id);
        setAttrs(searchInfo);
        setAttr("curr_org_id",InterfaceUtil.getOrgId());
        findByPageForSearch(BusinessAuthConfigService.service.getSpreadMemberThemeSqlSelect(),
                            BusinessAuthConfigService.service.getSpreadMemberThemeSqlExceptSelect(searchInfo));
        render("/admin/spreadmember/theme_auth_config_list.tpl");
    }

    /**
     * 人员导入模板下载
     */
    public void template(){
        renderFile(URL_TEMPLATE);
    }

    /**
     * 新增主题权限配置初始化
     */
    public void addThemeAuthConfig(){
        addAuthConfig(ENTER_TYPE_THEME);
    }

    /**
     * 获取主题渠道类数据展示对话框
     */
    public void dialogChannelTheme(){
        dialogChannel(ENTER_TYPE_THEME);
    }

    /**
     * 获取主题地市类数据展示对话框
     */
    public void dialogCityTheme(){
        dialogCity(ENTER_TYPE_THEME);
    }

    /**
     * 获取主题门店类数据展示对话框
     */
    public void dialogStoreTheme(){
        dialogStore(ENTER_TYPE_THEME);
    }

    /**
     * 获取主题门店类数据展示对话框
     */
    public void dialogMemberTheme(){
        dialogMember(ENTER_TYPE_THEME);
    }


    /**
     * 修改主题权限配置初始化
     */
    public void editThemeAuthConfig(){
        editAuthConfig(ENTER_TYPE_THEME);
    }

    /*
     * 跳转到主题数据业务配置页面
     */
    public void toThemeAuthConfigData(){
        setAttr(KEY_FLOW_ID, getPara(KEY_FLOW_ID, ""));
        initTheme();
        render("/admin/spreadmember/theme_auth_config_data.tpl");
    }

    /**
     * 已配置权限列表中删除一条权限配置数据
     */
    public void deleteThemeAuthConfig(){
        renderJson(deleteAuthConfig());
    }

    private void initTheme(){
        List<Record> list = BusinessAuthConfigService.service.getThemeList();
        setAttr("themeList", list);
        String themeArr = JsonKit.toJson(list);
        setAttr("themeArr", themeArr);
    }

    // ------------------------------------------业务权限配置部分--------------------------------------------------------------
    /**
     * TODO还没实现
     * 
     * @Title: businessList
     * @Description:分页获取泛店员业务权限配置数据列表
     */
    public void businessList(){
        initType();
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        if(!searchInfo.containsKey("org_id") || "-1".equals(searchInfo.get("org_id"))){
            searchInfo.put("org_id", InterfaceUtil.getOrgId() + "");
        }
        if(!searchInfo.containsKey(LIST_SELECT_TYPE)){
            searchInfo.put(LIST_SELECT_TYPE, getPara(LIST_SELECT_TYPE, "0"));
        }
        setAttrs(searchInfo);
        int org_id = Integer.parseInt(searchInfo.get("org_id"));
        setAttr("curr_org_id", org_id);
        Page pager = SpreadMemberAuthConfigService.service.getBusinessAuthListByPage(getParaToInt(PAGE_NUMBER, 1),
                getParaToInt(PAGE_SIZE, 10),searchInfo,Integer.parseInt(searchInfo.get(LIST_SELECT_TYPE)));
        setAttr(PAGER,pager);
        render("/admin/spreadmember/business_auth_config_list.tpl");
    }

    /**
     * 新增业务权限配置初始化
     */
    public void addBusinessAuthConfig(){
        addAuthConfig(ENTER_TYPE_BUSINESS);
    }

    /**
     * 获取业务数据展示对话框
     */
    public void dialogChannelBusiness(){
        dialogChannel(ENTER_TYPE_BUSINESS);
    }


    /**
     * 获取业务数据展示对话框
     */
    public void dialogCityBusiness(){
        dialogCity(ENTER_TYPE_BUSINESS);
    }
    /**
     * 获取业务数据展示对话框
     */
    public void dialogStoreBusiness(){
        dialogStore(ENTER_TYPE_BUSINESS);
    }
    /**
     * 获取业务数据展示对话框
     */
    public void dialogMemberBusiness(){
        dialogMember(ENTER_TYPE_BUSINESS);
    }

    /**
     * 编辑业务权限配置初始化
     */
    public void editBusinessAuthConfig(){
        editAuthConfig(ENTER_TYPE_BUSINESS);
    }

    /**
     * 编辑业务权限配置初始化
     */
    public void deleteBusinessAuthConfig(){
        renderJson(deleteAuthConfig());
    }

    /*
     * 跳转到泛店员业务数据配置页面
     */
    public void toBusinessAuthConfigData(){
        setAttr(KEY_FLOW_ID, getPara(KEY_FLOW_ID, ""));
        initType();
        render("/admin/spreadmember/business_auth_config_data.tpl");
    }

    /**
     * 获取泛店员能够配置的业务模块
     * 
     * @Title: initType
     * @Description:TODO void
     */
    private void initType(){
        List<Record> list = BusinessAuthConfigService.service.getSpreadMemberBusinessTypeList();
        setAttr("businessTypeList", list);
    }

    /**
     * 根据泛店员业务类型值获取相应业务套餐数据
     * 
     * @Title: loadBusiness
     * @Description:TODO void
     */
    public void loadBusiness(){
        JSONArray busDatas = new JSONArray();
        String actType = getPara("actType", "");
        logger.info("actType = " + actType);
        if(StrKit.isBlank(actType)){
            logger.error("-----actType isBlank-----");
            renderJson(busDatas);
            return;
        }
        // 根据类型值判断从哪个表取数据（1000以下属于资费类数据，否则属于非资费类数据）
        if(actType.length() < 4){
            // 活动类型值长度小于4位表示是资费类业务，通过类型值取资费大类（业务类型）和资费小类（业务数据）
            busDatas = getTariffDatas(actType);
            // logger.info("busDatas :" + busDatas.toString());
        } else{
            int businessType = Integer.parseInt(actType);
            // 活动类型值长度大于4位（1000开始）表示是其他业务，如通用的宽带预约套餐、终端销售名称等，需要分别进行判断并在相应表取数据
            busDatas = BusinessAuthConfigService.service.getSpreadMemberBusinessData(businessType);
        }
        renderJson(busDatas);
    }

    /**
     * @Title: getTariffDatas
     * @Description:TODO
     * @param actType
     * @return JSONArray
     */
    private JSONArray getTariffDatas(String actType){
        List<Record> tariffClassList = TariffClassService.service.getTariffClassByActType(actType);
        JSONArray busDatas = TariffService.service.getTariffByTariffClass(tariffClassList);

        return busDatas;
    }

    // ------------------------------------------主题和业务权限配置共用部分--------------------------------------------------------------
    /**
     * @Title: addAuthConfig
     * @Description:TODO
     * @param enterType
     *            void
     */
    private void addAuthConfig(int enterType){
        int type = getParaToInt(KEY_TYPE, BusinessAuthConfigService.TYPE_CITY);// 默认tab展示地市
        setAttr(KEY_TYPE, type);

        String operation = getPara(KEY_OPERATION, BusinessAuthConfigService.OPERATION_ADD);
        setAttr(KEY_OPERATION, operation);
        String flowId = getPara(KEY_FLOW_ID);
        if(BusinessAuthConfigService.OPERATION_ADD.equalsIgnoreCase(operation)){
            if(StrKit.isBlank(flowId)){
                // 1.空表示从新增配置按钮过来，生成流水号
                flowId = BusinessAuthConfigService.service.createFlowId();
            }
            // 说明不是第一次刷新，保存现有的flowId
            setAttr(KEY_FLOW_ID, flowId);
        }

        int pageSize = getParaToInt(PAGE_SIZE, UI_PAGER_SIZE_DEFAULT);

        int channel_type_page_number = getParaToInt("channel_type_page_number", UI_PAGER_NUMBER_DEFAULT);
        int city_page_number = getParaToInt("city_page_number", UI_PAGER_NUMBER_DEFAULT);
        int store_page_number = getParaToInt("store_page_number", UI_PAGER_NUMBER_DEFAULT);
        int member_page_number = getParaToInt("member_page_number", UI_PAGER_NUMBER_DEFAULT);

        ConcurrentHashMap<String, String> map = getSearchInfo();

        setAttr("typePager", SpreadMemberAuthConfigService.service.queryChannelTypeTemp(channel_type_page_number, pageSize,
                                                                                    map, flowId));

        setAttr("cityPager", BusinessAuthConfigService.service.queryChannelCityTemp(city_page_number, pageSize,
                map, flowId));


        setAttr("storePager", BusinessAuthConfigService.service.queryChannelStoreTemp(store_page_number, pageSize,
                map, flowId));


        setAttr("memberPager", BusinessAuthConfigService.service.queryChannelMemberTemp(member_page_number, pageSize,
                map, flowId));


        if(ENTER_TYPE_THEME == enterType){// 新增主题权限配置
            render("/admin/spreadmember/theme_auth_config_input.tpl");
        } else{// 新增业务权限配置
            render("/admin/spreadmember/business_auth_config_input.tpl");
        }
    }

    /**
     * @Title: dialogChannel
     * @Description:TODO
     * @param enterType
     *            void
     */
    private void dialogChannel(int enterType){
        int pageNumber = getParaToInt(PAGE_NUMBER, 1);
        int pageSize = getParaToInt(PAGE_SIZE, 10);
        ConcurrentHashMap<String, String> map = getSearchInfo();
        int type = getParaToInt(KEY_TYPE);// 根据这个查询是渠道大类，渠道簇还是渠道小类type-3即是对应的层级
        setAttr(KEY_TYPE, type);
        String operation = getPara(KEY_OPERATION);
        setAttr(KEY_OPERATION, operation);
        String flowId = getPara(KEY_FLOW_ID);
        setAttr(KEY_FLOW_ID, flowId);
        Page<Record> page = BusinessAuthConfigService.service.getChannel(type, pageNumber, pageSize, map);
        setAttr(Constant.Ui.PAGER, page);


        //获取所有地市列表
        List<Organization> cityList= Organization.dao.getOrganizationCityList(InterfaceUtil.getOrgId());
        setAttr("cityList",cityList);
        if(ENTER_TYPE_THEME == enterType){// 主题权限配置
            render("/admin/spreadmember/theme_auth_config_dialog_channel.tpl");
        } else{// 业务权限配置
            render("/admin/spreadmember/business_auth_config_dialog_channel.tpl");
        }
    }



    /**
     * @Title: dialogChannel
     * @Description:TODO
     * @param enterType
     *            void
     */

    public void dialogCity(int enterType){
        int pageNumber = getParaToInt(Constant.Ui.PAGER_NUMBER, 1);
        int pageSize = getParaToInt(Constant.Ui.PAGER_SIZE, 10);

        String operation = getPara(KEY_OPERATION);
        setAttr(KEY_OPERATION, operation);
        String flowId = getPara(KEY_FLOW_ID);
        setAttr(KEY_FLOW_ID, flowId);
        int type = getParaToInt(KEY_TYPE);
        setAttr(KEY_TYPE, type);
        int configBusinessId = getParaToInt(KEY_BUSINESS_ID, 0);
        int creatorOrgId = getParaToInt(KEY_CREATOR_ORG_ID, 0);
        setAttr(KEY_BUSINESS_ID, configBusinessId);
        setAttr(KEY_CREATOR_ORG_ID, creatorOrgId);

        ConcurrentHashMap<String, String> map = getSearchInfo();

        setAttr(Constant.Ui.PAGER, SpreadMemberAuthConfigService.service.getCity(pageNumber, pageSize, map, operation,
                configBusinessId, creatorOrgId, flowId));
        //render("/admin/business_auth_config_dialog_city.tpl");



        if(ENTER_TYPE_THEME == enterType){// 主题权限配置
            render("/admin/spreadmember/theme_auth_config_dialog_city.tpl");
        } else{// 业务权限配置
            render("/admin/spreadmember/business_auth_config_dialog_city.tpl");
        }
    }
    /**
     * @Title: dialogChannel
     * @Description:TODO
     * @param enterType
     *            void
     */

    public void dialogStore(int enterType){
        int pageNumber = getParaToInt(Constant.Ui.PAGER_NUMBER, 1);
        int pageSize = getParaToInt(Constant.Ui.PAGER_SIZE, 10);

        String operation = getPara(KEY_OPERATION);
        setAttr(KEY_OPERATION, operation);
        String flowId = getPara(KEY_FLOW_ID);
        setAttr(KEY_FLOW_ID, flowId);
        int type = getParaToInt(KEY_TYPE);
        setAttr(KEY_TYPE, type);
        int configBusinessId = getParaToInt(KEY_BUSINESS_ID, 0);
        int creatorOrgId = getParaToInt(KEY_CREATOR_ORG_ID, 0);
        setAttr(KEY_BUSINESS_ID, configBusinessId);
        setAttr(KEY_CREATOR_ORG_ID, creatorOrgId);

        ConcurrentHashMap<String, String> map = getSearchInfo();

        setAttr(Constant.Ui.PAGER, BusinessAuthConfigService.service.getStore(pageNumber, pageSize, map));

        if(ENTER_TYPE_THEME == enterType){// 主题权限配置
            render("/admin/spreadmember/theme_auth_config_dialog_store.tpl");
        } else{// 业务权限配置
            render("/admin/spreadmember/business_auth_config_dialog_store.tpl");
        }
    }

    public void dialogMember(int enterType){
        int pageNumber = getParaToInt(Constant.Ui.PAGER_NUMBER, 1);
        int pageSize = getParaToInt(Constant.Ui.PAGER_SIZE, 10);

        String operation = getPara(KEY_OPERATION);
        setAttr(KEY_OPERATION, operation);
        String flowId = getPara(KEY_FLOW_ID);
        setAttr(KEY_FLOW_ID, flowId);
        int type = getParaToInt(KEY_TYPE);
        setAttr(KEY_TYPE, type);
        int configBusinessId = getParaToInt(KEY_BUSINESS_ID, 0);
        int creatorOrgId = getParaToInt(KEY_CREATOR_ORG_ID, 0);
        setAttr(KEY_BUSINESS_ID, configBusinessId);
        setAttr(KEY_CREATOR_ORG_ID, creatorOrgId);

        ConcurrentHashMap<String, String> map = getSearchInfo();

        setAttr(Constant.Ui.PAGER, SpreadMemberAuthConfigService.service.getMemberSpreader(pageNumber, pageSize, map));

        if(ENTER_TYPE_THEME == enterType){// 主题权限配置
            render("/admin/spreadmember/theme_auth_config_dialog_member.tpl");
        } else{// 业务权限配置
            render("/admin/spreadmember/business_auth_config_dialog_member.tpl");
        }
    }



    /**
     * @Title: editAuthConfig
     * @Description:TODO
     * @param enterType
     *            void
     */
    private void editAuthConfig(int enterType){
        int config_business_id = getParaToInt(KEY_BUSINESS_ID, 0);
        int config_business = getParaToInt(KEY_BUSINESS, 0);
        int creator_org_id = getParaToInt(KEY_CREATOR_ORG_ID, 0);
        setAttr(KEY_BUSINESS_ID, config_business_id);
        setAttr(KEY_CREATOR_ORG_ID, creator_org_id);
        setAttr(KEY_BUSINESS, config_business);
        int type = getParaToInt(KEY_TYPE, BusinessAuthConfigService.TYPE_CITY);// 默认tab展示渠道
        setAttr(KEY_TYPE, type);
        int pageSize = getParaToInt(PAGE_SIZE, 10);
        setAttr(KEY_OPERATION, BusinessAuthConfigService.OPERATION_EDIT);
        setAttr(KEY_FLOW_ID, "");
        ConcurrentHashMap<String, String> map = getSearchInfo();

        setAttr("typePager",
                SpreadMemberAuthConfigService.service
                        .getSpreadMemberChannelTypePagerForRegular(getParaToInt("channel_type_page_number", 1),
                                                                   pageSize, config_business_id, creator_org_id, map,config_business));

        setAttr("cityPager",
                BusinessAuthConfigService.service
                        .getSpreadMemberCityPagerForRegular(getParaToInt("city_page_number", 1),
                                pageSize, config_business_id, creator_org_id, map));

        setAttr("storePager",
                BusinessAuthConfigService.service
                        .getSpreadMemberStorePagerForRegular(getParaToInt("store_page_number", 1),
                                pageSize, config_business_id, creator_org_id, map));

        setAttr("memberPager",BusinessAuthConfigService.service.getSpreadMemberPagerForRegular(getParaToInt("member_page_number", 1),
                                pageSize, config_business_id, creator_org_id, map));


        if(ENTER_TYPE_THEME == enterType){// 编辑主题权限配置
            render("/admin/spreadmember/theme_auth_config_input.tpl");
        } else{// 编辑业务权限配置
            render("/admin/spreadmember/business_auth_config_input.tpl");
        }
    }

    /**
     * 
     * @Title: deleteAuthConfig
     * @Description:TODO
     * @return JSONObject
     */
    private JSONObject deleteAuthConfig(){
        String[] ids = getParaValues("ids");
        if(ids == null || ids.length <= 0){
            ajaxJsonErrorMessage("删除失败，无选中项");
        }
        int delCount = 0;
        for(String id : ids){
            if(id.contains("#%#")){
                String[] idArr = id.split("#%#");
                int config_business_id = Integer.parseInt(idArr[0]);
                int creator_org_id = Integer.parseInt(idArr[1]);
                int resultDelete = new BusinessAuthConfigService().service
                        .deleteSpreadMemberAuthConfig(config_business_id, creator_org_id);
                if(resultDelete > 0)
                    delCount++;
            }
        }
        String message = "";
        int code = 1005;
        if(delCount == ids.length){
            message = "删除成功";
            code = 1000;
        } else if(delCount > 0 && delCount < ids.length){
            message = "部分数据删除失败";
            code = 1000;
        } else{
            message = "删除失败";
        }
        JSONObject json = new JSONObject();
        json.put("resultCode", code);
        json.put("message", message);

        return json;
    }

    /**
     * 新增，按照地市、门店、人员、渠道大类、渠道簇、渠道小类配置
     */
    public void addAuthOrizationByType(){
        String flowId = getPara(KEY_FLOW_ID);
        int type = getParaToInt(KEY_TYPE);
        String operation = getPara(KEY_OPERATION);
        Integer[] ids = Utils.string2Int(getPara(KEY_IDS), "#");
        boolean ret = false;
        if(BusinessAuthConfigService.OPERATION_ADD.equalsIgnoreCase(operation)){// 新增的新增
            ret = BusinessAuthConfigService.service.saveByTypeTemp(flowId, type, ids);
        } else if(BusinessAuthConfigService.OPERATION_EDIT.equalsIgnoreCase(operation)){// 编辑的新增
            int business = getParaToInt(KEY_BUSINESS);
            int businessId = getParaToInt(KEY_BUSINESS_ID);
            int creatorOrgId = getParaToInt(KEY_CREATOR_ORG_ID, 0);
            ret = BusinessAuthConfigService.service.saveSpreadMemberByType(type, ids, business, businessId,
                                                                           creatorOrgId);
        }
        if(ret){
            ajaxJsonSuccessMessage("OK");
        } else{
            ajaxJsonErrorMessage("FAIL");
        }
    }


    /**
     * 新增，按照地市、门店、人员、渠道大类、渠道簇、渠道小类配置
     */
    public void addAuthOrizationByTypeWithChannel(){
        String flowId = getPara(KEY_FLOW_ID);
        int type = getParaToInt(KEY_TYPE);
        String operation = getPara(KEY_OPERATION);
        Integer[] ids = string2Int(getPara(KEY_IDS), "#");
        Integer[] cityOrgIds = string2Int(getPara("cityOrgIds"), ",");
        if(cityOrgIds.length < 1){
            List<Organization> list = Organization.dao.getOrganizationCityList(InterfaceUtil.getOrgId());
            cityOrgIds = new Integer[list.size()];
            for (int i = 0; i < list.size(); i++) {
                cityOrgIds[i] = list.get(i).get(Organization.ID);
            }
        }
        boolean ret = false;
        if(BusinessAuthConfigService.OPERATION_ADD.equalsIgnoreCase(operation)){// 新增的新增
            ret = SpreadMemberAuthConfigService.service.saveByTypeTemp(flowId, type, ids,cityOrgIds);
        } else if(BusinessAuthConfigService.OPERATION_EDIT.equalsIgnoreCase(operation)){// 编辑的新增
            int business = getParaToInt(KEY_BUSINESS);
            int businessId = getParaToInt(KEY_BUSINESS_ID);
            int creatorOrgId = getParaToInt(KEY_CREATOR_ORG_ID, 0);
            ret = SpreadMemberAuthConfigService.service.saveSpreadMemberByType(type, ids,cityOrgIds, business, businessId,
                    creatorOrgId);
        }
        if(ret){
            ajaxJsonSuccessMessage("OK");
        } else{
            ajaxJsonErrorMessage("FAIL");
        }
    }


    /**
     * 统一的删除方法,通过operation区分，由于设计的原因，新增的删除的id是关系表的id，编辑的删除id是实体类的id
     */
    public void deleteAuthorization(){
        Integer[] ids = string2Int(getPara(KEY_IDS), "#");
        String operation = getPara(KEY_OPERATION);
        int type = getParaToInt(KEY_TYPE);
        setAttr(KEY_OPERATION, operation);
        setAttr(KEY_TYPE, type);
        boolean ret = false;
        if(BusinessAuthConfigService.OPERATION_ADD.equalsIgnoreCase(operation)){// 新增的删除
            String flowId = getPara(KEY_FLOW_ID);
            if(type==6){
                ret = BusinessAuthConfigService.service.deleteByChannelTemp(ids);
            }else{
                ret = BusinessAuthConfigService.service.deleteByTypeTemp(type, flowId, ids);
            }
        } else if(BusinessAuthConfigService.OPERATION_EDIT.equalsIgnoreCase(operation)){// 编辑的删除
            ret = BusinessAuthConfigService.service.deleteSrpeadMemberAuthConfigByType(ids);
        }
        if(ret){
            ajaxJsonSuccessMessage("OK");
        } else{
            ajaxJsonErrorMessage("FAIL");
        }
    }

    public void saveConfigData(){
        String businessStr = getPara(KEY_BUSINESS, null);
        if(StrKit.notBlank(businessStr)){
            int business = Integer.parseInt(businessStr);
            Integer[] ids = getParaValuesToInt(KEY_IDS);
            String flowId = getPara(KEY_FLOW_ID);
            logger.info("business=" + business + ",flowId=" + flowId + ",ids=" + Arrays.toString(ids));
            BusinessAuthConfigService service = Duang.duang(BusinessAuthConfigService.class, Tx.class);
            boolean result = false;
            try{
                result = service.saveSpreadMemberConfig(business, flowId, ids);
            }
            catch(Exception e){
                e.printStackTrace();
            }
            if(result){
                ajaxJsonSuccessMessage("OK");
            } else{
                ajaxJsonErrorMessage("FAIL");
            }
        } else{
            logger.error("config_business is null or blank!");
        }
    }

    /**
     * 1#2#3#4
     */
    public Integer[] string2Int(String ids, String token){
        if(StrKit.isBlank(ids)){
            return new Integer[0];
        }
        String[] strings = ids.split(token);
        Integer[] result = new Integer[strings.length];
        for(int i = 0; i < result.length; i++)
            result[i] = Integer.parseInt(strings[i]);
        return result;
    }


    /**
     * 一键删除当前配置中所有人员信息
     */
    public void deleteAllMemberAuthCfg(){
        String operation = getPara(KEY_OPERATION);
        int type = getParaToInt(KEY_TYPE);
        setAttr(KEY_OPERATION, operation);
        setAttr(KEY_TYPE, type);

        int deleteResult=0;
        if(BusinessAuthConfigService.OPERATION_ADD.equalsIgnoreCase(operation)){
            String flowId = getPara(KEY_FLOW_ID);
            setAttr(KEY_FLOW_ID, flowId);
            deleteResult = SpreadMemberAuthConfigService.service.deleteAllMemberForBusinessAuthConfigTemp(type,flowId);
        }else if(BusinessAuthConfigService.OPERATION_EDIT.equalsIgnoreCase(operation)){
            int configBusiness = getParaToInt(KEY_BUSINESS);
            int configBusinessId = getParaToInt(KEY_BUSINESS_ID);
            int creatorOrgId = getParaToInt(KEY_CREATOR_ORG_ID,InterfaceUtil.getOrgId());
            setAttr(KEY_BUSINESS,configBusiness);
            setAttr(KEY_BUSINESS_ID,configBusinessId);
            setAttr(KEY_CREATOR_ORG_ID,creatorOrgId);
            deleteResult = SpreadMemberAuthConfigService.service.deleteAllMemberForSpreadAuthConfig(type,configBusiness,configBusinessId,creatorOrgId);
        }
        if(deleteResult > 0){
            ajaxJsonSuccessMessage("OK");
        } else{
            ajaxJsonErrorMessage("FAIL");
        }
    }









    /**
     * 人员导入
     */
    public void upload(){
        String result = null;
        int status = 1;
        try{
            result = importMemberData();
        }
        catch(OfficeXmlFileException | EncryptedDocumentException | InvalidFormatException e){
            e.printStackTrace();
            result = "格式错误，请上传excel 2003/2007格式文件";
            status = 0;
        }
        catch(Exception e){
            e.printStackTrace();
            result = "导入数据失败,请联系管理员.";
            status = 0;
        }
        finally{
            Map<String, Object> jsonMap = new HashMap<String, Object>();
            jsonMap.put("status", status);
            jsonMap.put("result", result);
            render(new JsonRender(jsonMap).forIE());
        }
    }
    private String importMemberData()
            throws FileNotFoundException, EncryptedDocumentException, InvalidFormatException{
        int successCount = 0;
        String errorMsg = " ";
        InputStream inputStream = new FileInputStream(getFile().getFile());
        ExcelLogs logs = new ExcelLogs();
        Collection<Map> importExcel = ExcelUtil.importExcel(Map.class, inputStream, "yyyy/MM/dd HH:mm:ss", logs, 0);
        String operation = getPara(KEY_OPERATION);
        setAttr(KEY_OPERATION,operation);
        int type = getParaToInt(KEY_TYPE);
        setAttr(KEY_TYPE,type);
        int configBusinessId = getParaToInt("config_business_id",0);
        setAttr("config_business_id",configBusinessId);
        int configBusiness = getParaToInt("config_business",0);
        setAttr("config_business",configBusiness);
        int creatorOrgId = getParaToInt("creator_org_id",InterfaceUtil.getAdminId());
        setAttr("creator_org_id",creatorOrgId);
        String flowId = getPara(KEY_FLOW_ID);
        setAttr(KEY_FLOW_ID,flowId);
        int i = 1;

        int loginOrgId = getParaToInt("org_id",InterfaceUtil.getOrgId());
        Map<Integer,Integer> orgIdMap = InterfaceUtil.getOrganizationReturnIntegerMap(loginOrgId);

        for(Map<?, ?> m : importExcel){
            String prefix = "\r\n第 " + i + " 条：";
            i++;
            if(!validImportExcelCellData(m)){
                errorMsg += prefix + "姓名、工号、手机号不能为空！";
                continue;
            }
            String name = getString(ExcelUtil.removeSpace(String.valueOf(m.get("姓名"))));
            String empCode = getString(ExcelUtil.removeSpace(String.valueOf(m.get("工号"))));
            String phoneNumber = getString(ExcelUtil.removeSpace(String.valueOf(m.get("手机号"))));
            MemberOrg member = MemberOrg.dao.getMemberOrgbyUserNameAndEmpCodeAndName(phoneNumber,empCode,name);
            if(member == null){
                errorMsg += prefix + "手机号" + phoneNumber + "，工号"+empCode+" 对应人员信息在大掌柜后台不存在";
                continue;
            }
            int orgMemberId = member.getInt(MemberOrg.ORG_ID);
            if(!orgIdMap.containsKey(orgMemberId)){
                errorMsg += prefix + "手机号" + phoneNumber + "，工号"+empCode+" 对应人员你无权限操作";
                continue;
            }
            if(member.getInt(MemberOrg.MEMBER_TYPE)!=3){
                errorMsg += prefix + "手机号" + phoneNumber + "，工号"+empCode+" 对应人员不是泛店员";
                continue;
            }

            int memberOrgId = member.getInt(MemberOrg.ID);
            if("add".equalsIgnoreCase(operation)){
                //查询数据是否已存在，存在就直接跳过
                String selectExistData = "select * from "+Constant.Table.TABLE_BUSINESS_AUTH_CONFIG_TEMP+" WHERE " +
                        "flow_id=? AND config_type=?" +
                        " AND config_type_id=? ";
                Record record = Db.findFirst(selectExistData,flowId,3,memberOrgId);
                if(record!=null && record.getInt("id")>0){
                    errorMsg += prefix + "该员工已授权，无需重复授权";
                    continue;
                }
                BusinessAuthConfigTemp bt = new BusinessAuthConfigTemp();
                bt.set(BusinessAuthConfigTemp.FLOW_ID,flowId);
                bt.set(BusinessAuthConfigTemp.CONFIG_TYPE,3);//3代表人员授权
                bt.set(BusinessAuthConfigTemp.CONFIG_TYPE_ID,memberOrgId);
                if(!bt.save()){
                    errorMsg += prefix + "保存到数据库时发生错误";
                    continue;
                }
            } else if("edit".equalsIgnoreCase(operation)){
                //查询数据是否已存在，存在就直接跳过
                String selectExistData = "select * from "+Constant.Table.TABLE_SPREAD_MEMBER_AUTH_CONFIG+" WHERE config_type=? AND config_type_id=?" +
                        " AND config_business=? AND config_business_id=? AND creator_org_id=? ";
                Record record = Db.findFirst(selectExistData,3,memberOrgId,configBusiness,configBusinessId,creatorOrgId);
                if(record!=null && record.getInt("id")>0){
                    errorMsg += prefix + " 该员工已授权，无需重复授权";
                    continue;
                }
                SpreadMemberAuthConfig b = new SpreadMemberAuthConfig();
                b.set(BusinessAuthConfig.CONFIG_TYPE,3);//3代表人员授权
                b.set(BusinessAuthConfig.CONFIG_TYPE_ID,memberOrgId);
                b.set(BusinessAuthConfig.CONFIG_BUSINESS,configBusiness);
                b.set(BusinessAuthConfig.CONFIG_BUSINESS_ID,configBusinessId);
                b.set(BusinessAuthConfig.CREATOR_ORG_ID,creatorOrgId);
                b.set(BusinessAuthConfig.UPDATED_TIME,new Date());
                if(!b.save()){
                    errorMsg += prefix + "保存到数据库时发生错误";
                    continue;
                }
            }
            successCount++;
        }
        int failedCount = importExcel.size() - successCount;
        if((failedCount > 0) && (errorMsg.length() > 200)){
            errorMsg = errorMsg.substring(0, 200) + "\r\n。。。。。。";
        }
        return "成功：" + successCount + "条," + "失败：" + failedCount + "条。" + (failedCount > 0 ? errorMsg : "");
    }
    private boolean validImportExcelCellData(Map<?, ?> data){
        String name = String.valueOf(data.get("姓名"));
        String empCode = String.valueOf(data.get("工号"));
        String phoneNumber = String.valueOf(data.get("手机号"));
        if(StringUtils.isBlank(name) || "null".equalsIgnoreCase(name) || StringUtils.isBlank(empCode)
                || "null".equalsIgnoreCase(empCode)|| StringUtils.isBlank(phoneNumber)
                || "null".equalsIgnoreCase(phoneNumber)){
            logger.error("validImportExcelCellData Data error");
            return false;
        }
        return true;
    }

    private String getString(String fullString){
        if(StringUtils.isBlank(fullString) || "null".equalsIgnoreCase(fullString)){
            return "";
        }
        return fullString;
    }

}
